package cz.movie.subRenamer;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.movie.subRenamer.model.FileRepresentation;
import cz.movie.subRenamer.util.FileNameUtil;
import cz.movie.subRenamer.util.LoadConfigUtil;
import cz.movie.subRenamer.worker.CoreWorker;
import cz.movie.subRenamer.worker.SubtitleWorker;
import cz.movie.subRenamer.worker.impl.CoreWorkerImpl;
import cz.movie.subRenamer.worker.impl.SubtitleWorkerImpl;

public class SubtitleRenamerImpl implements SubtitleRenamer {

	static final Logger logger = LoggerFactory.getLogger(SubtitleRenamerImpl.class);

	public SRConfiguration loadDefaultConfig() {
		SRConfiguration config = new SRConfiguration();

		try {
			LoadConfigUtil loader = new LoadConfigUtil("config.xml");
			config.setRenameMovies(loader.isRenameMovieFiles());
			config.setRules(loader.loadPatterns());
			config.setDeleteEmptyDirs(loader.isDeleteEmptyDirs());
			config.setExtract(loader.isExtract());
			config.setLanguages(loader.loadLanguages());
			config.setOutputString(loader.getOutputString());
			config.setDefaultSubtitleLanguage(loader.getDefaultSubtitleLanguage());
		} catch (Exception e) {
			logger.error("Cannot load configuration");
			e.printStackTrace();
			return null;
		}
		return config;
	}

	public void process(String dir, SRConfiguration config) {
		File sourceDir = new File(dir);
		if (!sourceDir.exists()) {
			logger.error("Folder {} does not exist", dir);
			return;
		}
		logger.info("process started in {}", dir);

		SubtitleWorker sw = new SubtitleWorkerImpl(config.getLanguages());
		CoreWorker core = new CoreWorkerImpl(config.getRules(), config.getOutputString());

		List<FileRepresentation> allMediaFiles;
		List<FileRepresentation> movies;

		if (config.isExtract()) {
			sw.extractAllSubtitles(sourceDir);
		}
		allMediaFiles = core.convertFileToRepresentation(FileNameUtil.getAllFilesForDir(sourceDir));
		sw.addLanguageToSubtitles(allMediaFiles);

		movies = core.assingSubtitlesToMovies(allMediaFiles);
		if (config.isRenameMovies()) {
			core.renameMovies(movies, config.getRemoveFromName());
		}
		core.renameAndMoveSubtitles(movies, config.getDefaultSubtitleLanguage());
		if (config.isDeleteEmptyDirs()) {
			FileNameUtil.deleteAllEmptyFolders(sourceDir);
		}
		logger.info("process end");
	}

}
